package com.gitee.ykr.lightweight.rpc.loadbalance;

import com.gitee.ykr.lightweight.rpc.common.delegate.NettyRpcDelegateImpl;
import com.gitee.ykr.lightweight.rpc.common.entity.NettyClient;
import com.gitee.ykr.lightweight.rpc.common.exception.CommonException;
import com.gitee.ykr.lightweight.rpc.registar.RpcClientEntity;


import java.util.ArrayList;
import java.util.List;

/**
 * @author YKR
 * @Describe
 * @date 2021/8/24
 */
public abstract class AbstractLoadBalanceExecutor extends NettyRpcDelegateImpl implements LoadBalanceExcutor {


    @Override
    public RpcClientEntity loadBalance(RpcClientEntity rpcClientEntity, String interfaceName) {
        List<NettyClient> clients = null;
        //先从注册中心获取实例集合
        if (excutorContainer.getClientDiscovery() != null) {
            clients = excutorContainer.getClientDiscovery().getNettyClietMap().get( rpcClientEntity.getName() );
        }
        //如果没有就从配置中获取
        if (clients == null) {
            clients = nettyRpcProperties.getClients();
        }
        List<NettyClient> candidates = null;
        if (clients != null && clients.size() > 0) {
            candidates = findCandidateClients( rpcClientEntity.getName(), clients );
        }
        if (candidates == null) {
            System.out.println(String.format("netty client host or port is null"));
            throw new CommonException( "netty client host or port is null" );
        }
        return loadBalance( rpcClientEntity, interfaceName, candidates );
    }

    //TODO 这一步可以做缓存，减少遍历，暂缓
    private List<NettyClient> findCandidateClients(String name, List<NettyClient> list) {

        List<NettyClient> candidates = new ArrayList<>();
        for (NettyClient client : list) {
            if (name.equals( client.getName() )) {
                candidates.add( client );
            }
        }
        return candidates;

    }

    protected abstract RpcClientEntity loadBalance(RpcClientEntity rpcClientEntity, String interfaceName, List<NettyClient> candidates);
}

